<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div{
            width: 20rem;
            height: 20rem;
            margin: 10rem auto;
            border: 1px solid red;
        }
        @keyframes shake{
            0%{transform: rotate(0);}
            25%{transform: rotate(-30deg);}
            50%{transform: rotate(0);}
            75%{transform: rotate(30deg);}
            100%{transform: rotate(0);}
        }
    </style>
</head>
<body>
    <div></div>
    <script>
        const oDiv=document.querySelector('div');
        let oldX=0;
        let oldY=0;
        let oldZ=0;

        //console.log(window.DeviceMotionEvent) 
        //oDiv.innerHTML=window.DeviceMotionEvent;
        //if(window.DeviceMotionEvent){ //检测是不是高级浏览器
            window.addEventListener('devicemotion',(ev)=>{//监测摇晃的事件
                oDiv.innerHTML='用户摇了'
                let acc=ev.accelerationIncludingGravity;//重力感应
                //x y z  三个轴的重力加速度
                oDiv.innerHTML=JSON.stringify(acc);
                if(Math.abs(acc.x-oldX)>20 || Math.abs(acc.y-oldY)>20 || Math.abs(acc.z-oldZ)>20){
                    oDiv.style.animation='shake linear 1s 3';
                }
            })
            oDiv.addEventListener('animationend',()=>{
                oDiv.style.animation='';
            })

            window.addEventListener("deviceorientation", function(event) {
                oDiv.innerHTML='用户摇了2'
            })
        //}
    </script>
</body>
</html>